package home;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;

import java.util.ArrayList;
import java.util.List;

import adapter.MainAdapter;
import base.BasePage;
import bean.MainFunBean;
import httptool.CommonUtil;
import httptool.QLParser;
import httptool.SharePrefUtil;
import httptool.getHttpUrl;
import httptool.takeUrlResource;
import pullrefreshview.PullToRefreshBase;
import pullrefreshview.PullToRefreshListView;
import shanshuitiancheng.news.R;
import shanshuitiancheng.news.WebViewActivity;

/**
 * Created by cch on 2016/6/14.
 */
public class FunctionPage extends BasePage{
    private PullToRefreshListView ptrLv;
    private MainAdapter  adapter;
    private String dataUrls;

    public FunctionPage(Context ct,String dataUrls){
        super(ct);
        this.dataUrls =dataUrls;
    }

    @Override
    //初始化view
    public View initView(LayoutInflater inflater) {
//        View view = inflater.inflate(R.layout.main_layout, null);//找到下拉刷新的布局文件
//        ptrLv = (PullToRefreshListView) view.findViewById(R.id.lv);//通过id找到下拉刷新的控件
//        // 上拉加载不可用
//        ptrLv.setPullLoadEnabled(false);
//        // 滚动到底自动加载可用
//        ptrLv.setScrollLoadEnabled(true);
//        setLastUpdateTime(); //设置最后更新时间
//
//        //设置一个刷新的点击事件
//        ptrLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
//            @Override
//            //下拉刷新数据
//            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
//                getJson(url, true);
//            }
//            @Override
//            //上拉加载数据
//            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//                getJson(more, false);
//            }
//        });
//        return view;
        View view = inflater.inflate(R.layout.main_layout,null);
        ptrLv = (PullToRefreshListView) view.findViewById(R.id.lv);
        ptrLv.setPullLoadEnabled(false);
        ptrLv.setScrollLoadEnabled(true);
        setLastUpdateTime();

        ptrLv.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MainFunBean.NewsBean newsBean;
//                if (ptrLv.getRefreshableView().getHeaderViewsCount() > 0) {
//                     newsBean = newsData.get(position);
//                } else {
//                    newsBean = newsData.get(position-1);
//                }
                Log.e("===============",position+"------");
                newsBean = newsData.get(position);
                Intent intent = new Intent(ct,WebViewActivity.class);
                intent.putExtra("url",newsBean.getUrl());
                ct.startActivity(intent);

            }
        });
        ptrLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getJson(dataUrls, true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getJson(more, false);
            }
        });
        return  view;
    }


    @Override
    public void initData() {
        String data = SharePrefUtil.getString(ct,dataUrls, "");//本地缓存区获取数据

        //如果数据为空就实行下拉刷新加载数据
        if(TextUtils.isEmpty(data)){
            getJson(dataUrls,true);
        } else {
            if(!data.contains("Warning")){
                MainFunBean datas = QLParser.parse(data, MainFunBean.class);//否者在MainFunBean中解析数据
                if(datas.getRetcode()==200){
                    List<MainFunBean.NewsBean> news = datas.getNews();//解析MainFunBean中的news数据
                    more = datas.getMore();
                    //判断adapter是否为空，如果为空就创建一个adapter
                    if(adapter==null){
                        adapter = new MainAdapter(news,ct);//将数据放入适配器中
                        ptrLv.getRefreshableView().setAdapter(adapter);
                    }
                }
            }


    }
    }

    private void onLoaded() {
        ptrLv.onPullDownRefreshComplete();  //上拉刷新完成
        ptrLv.onPullUpRefreshComplete();    //下拉刷新完成
    }

    //显示最后刷新时间
    private void setLastUpdateTime() {
        String text = CommonUtil.getStringDate();
        ptrLv.setLastUpdatedLabel(text);
    }


    private String more;

    private List<MainFunBean.NewsBean> newsData = new ArrayList<>();//设置List为全局变量

    //連網請求數據
    private void getJson(String urls, final boolean isFirst) {

        takeUrlResource.getJson(ct, urls, new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                if(!s.contains("Warning")){
                    //缓存本地数据
                    SharePrefUtil.saveString(ct,dataUrls,s);
                    //解析MainFunBean里面的数据
                    MainFunBean datas = QLParser.parse(s, MainFunBean.class);
                    if(datas.getRetcode()==200){
                        List<MainFunBean.NewsBean> news = datas.getNews();
                        //判断是否是第一次请求当前url数据
                        if(isFirst){
                            newsData.clear();
                            newsData.addAll(news);
                        }else {
                            newsData.addAll(news);
                        }

                        //获取下一页数据的URL
                        more = datas.getMore();
                        if(adapter==null){
                            adapter = new MainAdapter(newsData,ct);
                            ptrLv.getRefreshableView().setAdapter(adapter);
                        }else {
                            adapter.notifyDataSetChanged();
                        }

                    //加载完成
                        onLoaded();
                    //活的more字段的数据
                        ptrLv.setHasMoreData(true);
                        setLastUpdateTime();
                    }

                }

            }
        } );
    }
}
